/**
 * Main 'Module' For the Test Fire Extension.
 */

FBL.ns(function()
{
    with ( FBL )
    {
        //        const stateHolder = {};
        //        const panelURL = "chrome://firebug/content/panel.html";
        var stateHolder = Components.classes["@mozilla.org/appshell/appShellService;1"].
            getService(Components.interfaces.nsIAppShellService).hiddenDOMWindow;

        var testFire = stateHolder.TestFire;

        Firebug.TestFireExtension = extend(Firebug.Module,
        {
            getState: function()
            {
                return testFire.state;
            },

        /**
         * Called when the window is opened.
         */
            initialize: function()
            {

            },

        /**
         * Called when a new context is created.
         * This will occur both on startup of the browser and on the (re)enabling of the Firebug Extension,
         * as well as on the opening of child windows / tabs.
         *
         */
            initContext: function( context )
            {
                var x = "initContext: " + context;
            },

        /**
         * Called after a context is detached to a separate window;
         */
            reattachContext: function( context )
            {
                var x = "reattachContext: " + context;
            },

        /**
         * Called when a page is changed, the Firebug extension is disabled or the window is closed.
         */
            destroyContext: function( context, persistedState )
            {
                var x = ("destroyContext: " + context + " : " + persistedState);
            },

        /**
         * Called when attaching to a window (top-level or frame).
         */
            watchWindow: function( context, win )
            {
                testFire.initTestFireModule(this, context, win);
                try
                {
                    var fcn = UTIL.bindFixed(Firebug.TestFireExtension.doClickIntercept, this);
                    win.removeEventListener("click", fcn, true);
                    win.addEventListener("click", fcn, true);
                    if(win.parent == win)
                    {
                        var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
                        var nsiWin = wm.getMostRecentWindow(null);
                        if(!testFire.isMonitoringBrowserWindow(nsiWin, win))
                        {
                            testFire.monitorBrowserWindow(nsiWin, win);
                        }
                    }
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }
            },

        /**
         * Called when unwatching a window (top-level or frame).
         */
            unwatchWindow: function( context, win )
            {
                if(win.parent == win)
                {
                    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
                    var nsiWin = wm.getMostRecentWindow(null);
                    testFire.removeBrowserWindow(nsiWin);
                }
                testFire.destroyTestFireModule(this, context, win);
            },

            loadedContext: function( context )
            {
                var x = ("loadedContext");
            },

            showSidePanel: function( browser, panel )
            {

            },

        /**
         * Check all click events on the page for attempts by the user to select an object (ctrl+shift + right-click).
         * Abort the event if it matches and set the object under the curser to be the selected object (or navigate up
         * the tree until a selectable object is found).
         *
         */
            doClickIntercept: function( event )
            {
                try
                {
                    if ( event.button == 2 && event.shiftKey && event.altKey )
                    {

                        var node = FirebugContext.hoverNode;
                        if ( node )
                        {
                            this.setTargetNode(node);
                            event.stopPropagation();
                            event.preventDefault();
                        }
                    }
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }
            },


        /**
         * Called when the window is closed.
         */
            shutdown: function()
            {
                window.removeEventListener("blur", this.doOnClickStuff, true);
            }
            ,

        /**
         * Called once for each child panel of this module.
         *
         */
            showPanel: function( browser, panel )
            {
                try
                {
                    var isTestFireExtension = panel && panel.name == "TestFireTreePanel";
                    var TestFireExtensionButtons = browser.chrome.$("fbTestFireExtensionButtons");
                    collapse(TestFireExtensionButtons, !isTestFireExtension);
                    browser.chrome.setGlobalAttribute("cmd_setTargetObject", "visible", !isTestFireExtension);
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }

            },






        /**************************************************************************************************************/

       getFBL: function()
       {
           return FBL;
       },

        setTestFire: function(testFire){
            Firebug.TestFire = testFire;
            this.testFire = testFire;
        },













        /**************************************************************************************************************/


            _refresh: function()
            {
                this.refreshTargetTestMenu();
                FirebugContext.getPanel("TestFireTreePanel")._refresh();
                FirebugContext.getPanel("TestFireCodePanel")._refresh();
            },
        /**
         * Used when throwing away a testfire session.
         */
            reInitialize: function()
            {
                FirebugContext.getPanel("TestFireTreePanel").reInitialize();

            },

        /**
         * Set the current object that will have actions and assertions performed on it.
         * Uses the context passed to find the node of interest and calls setTargetNode(...)
         * Used from the right-click menu defined in FirebugOverlay.
         *
         * This is not application scoped due to the fact that the object would not
         * be available across windows anyway.
         *
         * @todo There is a bug here: the context.hoverNode will retrieve the node that the mouse is over.
         * this doesn't seem bad, until you realize that this value is set, not when the right-click action is done,
         * but when the menu-item is left-clicked. So you will often get a UI item which is totally unrelated
         * to what you right-clicked on.
         */
            setTargetObjectCommand: function( context )
            {
                try
                {
                    if ( context.hoverNode )
                    {
                        var node = context.hoverNode;
                        this.setTargetNode(node);
                    }
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }

            },

        /**
         * Set the current object that will have actions and assertions performed on it.
         */
            setTargetNode: function( node )
            {
                try
                {
                    if ( node && node.nodeType != 1 )
                    {
                        node = node.parentNode;
                    }
                    FirebugContext.getPanel("TestFireTreePanel").setTargetNode(node);
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }

            },





            refreshTargetTestMenu: function( callingPopup, event )
            {
                try
                {
                    var menupop = $("testFireTargetMenu");
                    if ( !callingPopup || menupop == event.originalTarget )
                    {
                        var testset = testFire.getTestset();
                        var selectedTest = testFire.getSelectedTest();
                        var ary = testset.getTests();
                        var menuItems = new Array();
                        for ( var i = 0; i < ary.length; i++ )
                        {
                            var command = FBL.bindFixed(testFire.setSelectedTest, testFire, ary[i]);
                            var select = ary[i] == selectedTest;
                            var mi = { nol10n: 1, name:"tf_target_group", label: ary[i].displayValue, type: "radio", command: command, checked:select};
                            menuItems.push(mi);
                        }
                        UTIL.populateMenu(menupop, menuItems);
                        testFire.setSelectedTest(selectedTest);

                    }
                    if(callingPopup)
                    {
                        return FirebugChrome.onOptionsShowing(callingPopup);
                    }
                }
                catch( ex )
                {tf_debug(ex); }

            },

            doRefreshBrowserCommands: function( caller, event )
            {
                try
                {
                    var popup = $("testFireBrowserCommandsPopup");
                    if ( popup == event.originalTarget )
                    {
                        var menuitems = this.getBrowserCommandMenuItems();
                        UTIL.populateMenu(caller, menuitems);
                    }
                    return FirebugChrome.onOptionsShowing(caller)
                }
                catch
                    ( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);

                }
                return true;

            },

            doRefreshAssertions: function( caller, event )
            {

                try
                {
                    var popup = $("testFireAssertionsMenu");
                    if ( popup == event.originalTarget )
                    {
                        var menuitems = FirebugContext.getPanel("TestFireTreePanel").getState().selectedTargetNodeWrapper.getAssertionMenuItems();
                        UTIL.populateMenu(caller, menuitems);
                    }
                    return FirebugChrome.onOptionsShowing(caller)
                }
                catch
                    ( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);

                }
                return true;

            },
            doRefreshActions: function( caller, event )
            {

                try
                {
                    var popup = $("testFireActionsMenu");
                    if ( popup == event.originalTarget )
                    {
                        var menuitems = FirebugContext.getPanel("TestFireTreePanel").getState().selectedTargetNodeWrapper.getActionMenuItems();
                        UTIL.populateMenu(caller, menuitems);
                    }
                    return FirebugChrome.onOptionsShowing(caller)
                }
                catch
                    ( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);

                }
                return true;

            },

            getBrowserCommandMenuItems: function( object, target )
            {
                try
                {
                    var finder = Browser
                    var asserts = new Array();
                    var tasks = new Array();
                    var currentActionList = testFire.getSelectedTest().testTasks;
                    var win = FirebugContext.window;
                    var items = new Array();
                    if ( currentActionList )
                    {
                        var itemNames = new Array();
                        for ( var name in finder )
                        {
                            itemNames.push(name);
                        }
                        itemNames.sort();
                        for ( var i = 0; i < itemNames.length; i++ )
                        {
                            var item = finder[itemNames[i]];
                            if ( item && item.assertable && item.assertable != 0 )
                            {
                                asserts.push(HtmlFinder.createMenuItem(finder, itemNames[i], win, currentActionList));
                            }
                            if ( item && item.actionable && item.actionable != 0 )
                            {
                                tasks.push(HtmlFinder.createMenuItem(finder, itemNames[i], win, currentActionList));
                            }
                        }
                        items.push({label: "Action", menuItems: tasks}, "-", {label:"Assert", menuItems: asserts});
                    }
                    return items;
                }
                catch( ex )
                {
                    Firebug.TestFire.util.tf_debug(ex);
                }

            }

        });
        Firebug.registerModule(Firebug.TestFireExtension);

    }
});